<template>
  <div class="userPage">
    <div class="left"></div>
    <div class="right">
      <div class="login">
        <form @submit.prevent="handleLogin">
          <div class="form">
            <div class="figure"></div>
            <div class="box">
              <div class="siteName">
                <dl>
                  <dt>
                    <i class="iconfont icon-health"></i>
                  </dt>
                  <dd>{ 病人信息后台中心 }</dd>
                </dl>
              </div>
              <div class="item">
                <div class="inputBox" :class="errors.username ? 'error' : ''">
                  <div class="iconfont icon-user"></div>
                  <input
                    type="text"
                    class="vInput"
                    v-model="formData.username"
                    autocomplete="new-password"
                    placeholder="请输入用户名"
                    @input="validateForm('username')"
                  />
                </div>
                <div class="error-tip" v-if="errors.username">
                  用户名不能为空
                </div>
              </div>
              <div class="item">
                <div class="inputBox" :class="errors.password ? 'error' : ''">
                  <div class="iconfont icon-lock"></div>
                  <input
                    type="password"
                    class="vInput"
                    v-model="formData.password"
                    autocomplete="new-password"
                    placeholder="请输入密码"
                    @input="validateForm('password')"
                  />
                </div>
                <div class="error-tip" v-if="errors.password">密码不能为空</div>
              </div>
              <div class="item">
                <div class="buttonBox">
                  <button class="vButton primary block" type="submit">
                    登录
                  </button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
<script setup>
import { useIndexStore } from "@/store/path";
import router from "@/route/index";
import { getCaptcha, login } from "@/api/index";
import { onMounted, ref, reactive } from "vue";
import { vToast } from "@/plugins/vToast";
const formData = reactive({
  username: "",
  password: "",
  captcha_code: "",
});
const errors = reactive({
  username: false,
  password: false,
  captcha_code: false,
});
const validateForm = (name) => {
  let isValid = true;
  if (name) {
    errors[name] = formData[name].trim() ? false : true;
  } else {
    errors.username = !formData.username.trim();
    errors.password = !formData.password.trim();
    isValid = Object.values(errors).every((v) => !v);
  }
  return isValid;
};
const indexStore = useIndexStore();
const captchaImg = ref(null);
indexStore.$patch({
  showLoading: false,
});
const getCaptchaImg = () => {
  getCaptcha().then((res) => {
    captchaImg.value = res;
    const blob = new Blob([res]);
    captchaImg.value = URL.createObjectURL(blob);
  });
};
const handleLogin = async () => {
  if (!validateForm()) return;

  try {
    const response = await login({
      username: formData.username,
      password: formData.password,
      // captcha_code: "1111",
    });

    if (response.code === 200) {
      console.log(response);
      if (response.data.isadmin === "1") {
        vToast({
          message: "登录成功,跳转中...",
          duration: 1000,
        }).then((res) => {
          indexStore.$patch({ token: response.data.token });
          sessionStorage.setItem("token", response.data.token);
          sessionStorage.setItem("username", response.data.username);
          setTimeout(() => {
            router.push({ name: "index" }).catch(err => console.log("路由跳转失败:", err));
          }, 200);
        });
      } else {
        vToast({
          message: "登录失败,无权限",
        }).then((res) => {
          indexStore.$patch({ token: null });
          sessionStorage.removeItem("token");
        });
      }
    } else {
      vToast({
        message: "登录失败" + response.msg,
      }).then((res) => {
        indexStore.$patch({ token: null });
        sessionStorage.removeItem("token");
      });
    }
  } catch (error) {
    vToast({
      message: "API请求错误:" + error,
    });
    getCaptchaImg(); // 失败时刷新验证码
  }
};
onMounted(() => {
  // getCaptchaImg();
});
</script>
<style lang="less">
@import url("@/assets/css/style.less");
</style>
<style lang="less" scoped>
.userPage {
  height: 100vh;
  width: 100vw;
  display: flex;
  background: #fafeff;
  .left {
    flex-grow: 1;
    background: url("@/assets/images/login.jpg") center no-repeat;
    border-right: rgba(0, 0, 0, 0.05) 1px solid;
    background-size: cover;
  }
  .right {
    width: 30vw;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
  }
  .login {
    display: flex;
    flex-direction: column;
    gap: 40px;
  }
}
.form {
  position: absolute;
  left: -600px;
  width: 1000px;
  min-height: 400px;
  background: #fff;
  top: 50%;
  border-radius: 8px;
  // border: #e8eaf0 1px solid;
  display: flex;
  transform: translateY(-50%);
    box-shadow: rgba(9, 30, 66, 0.14) 0px 4px 8px -2px,
      rgba(9, 30, 66, 0.04) 0px 0px 0px 1px;
  overflow: hidden;
  .figure {
    flex-grow: 1;
    background: url("@/assets/images/slogon.jpg") center;
    background-size: cover;
  }
  .box {
    width: 400px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 40px;
  }
  .item {
    position: relative;
    width: 320px;
    .error-tip {
      position: absolute;
      font-size: 14px;
      color: #d00;
      top: 50%;
      right: 14px;
      transform: translateY(-50%);
    }
  }
}
.siteName {
  font-size: 22px;
  font-weight: bold;
  color: var(--bs-theme-color);
  text-align: center;
  dl {
    display: flex;
    gap: 20px;
    justify-content: center;
    align-items: center;
    dt {
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
  }
}
.label {
  font-size: 13px;
  padding-bottom: 5px;
}
.captchaImg {
  height: 38px;
  border: #dce1e4 1px solid;
  border-radius: 4px;
  cursor: pointer;
}
.inputBox {
  height: 38px;
  padding-left: 30px;
  border-radius: 8px;
  background: #fff;
    box-shadow: rgba(9, 30, 66, 0.14) 0px 4px 8px -2px,
      rgba(9, 30, 66, 0.04) 0px 0px 0px 1px;
  &.error {
    box-shadow: rgba(200, 0, 0, 0.12) 0px 1px 3px,
      rgba(200, 0, 0, 0.24) 0px 1px 2px;
  }
  .iconfont {
    position: absolute;
    width: 38px;
    height: 38px;
    position: absolute;
    left: 0;
    top: 0;
    line-height: 38px;
    text-align: center;
    font-size: 18px;
    color: var(--bs-gray-color);
    opacity: 0.6;
  }
  input::placeholder {
    color: #c5c7d1;
  }
}
</style>